package cn.com.dcsgo.library.admin.mapper;

import cn.com.dcsgo.library.admin.domain.po.BorrowRecord;
import cn.com.dcsgo.library.admin.domain.vo.BorrowRecordVO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;

/**
 * @author Dcsgo
 * @since 2024-09-02
 */
@Mapper
public interface BorrowRecordsMapper extends BaseMapper<BorrowRecord> {
    @Select("SELECT u.name AS name, br.book_copies_id AS copyId, b.title AS title, br.borrow_date AS borrowDate, br.due_date AS dueDate, DATEDIFF(now(), br.borrow_date) AS borrowDays " +
            "FROM borrow_records br " +
            "JOIN book_copies c ON br.book_copies_id = c.id " +
            "JOIN books b ON c.book_id = b.id " +
            "JOIN users u ON br.user_id = u.id " +
            "WHERE br.status = 1 " +
            "AND (#{copyId} IS NULL OR br.book_copies_id = #{copyId}) " +
            "AND (#{title} IS NULL OR b.title LIKE CONCAT('%', #{title}, '%')) " +
            "AND (#{name} IS NULL OR u.name LIKE CONCAT('%', #{name}, '%')) " +
            "AND (#{minBorrowDate} IS NULL OR br.borrow_date >= #{minBorrowDate}) " +
            "AND (#{maxBorrowDate} IS NULL OR br.borrow_date <= #{maxBorrowDate}) " +
            "AND (#{minDueDate} IS NULL OR br.due_date >= #{minDueDate}) " +
            "AND (#{maxDueDate} IS NULL OR br.due_date <= #{maxDueDate}) " +
            "AND (#{minBorrowDays} IS NULL OR DATEDIFF(now(), br.borrow_date) >= #{minBorrowDays}) " +
            "AND (#{maxBorrowDays} IS NULL OR DATEDIFF(now(), br.borrow_date) <= #{maxBorrowDays})")
    Page<BorrowRecordVO> selectBorrowRecords(Page<BorrowRecordVO> page,
                                              @Param("copyId") Long copyId,
                                              @Param("title") String title,
                                              @Param("name") String name,
                                              @Param("minBorrowDate") LocalDateTime minBorrowDate,
                                              @Param("maxBorrowDate") LocalDateTime maxBorrowDate,
                                              @Param("minDueDate") LocalDateTime minDueDate,
                                              @Param("maxDueDate") LocalDateTime maxDueDate,
                                              @Param("minBorrowDays") Long minBorrowDays,
                                              @Param("maxBorrowDays") Long maxBorrowDays);

}
